(*DONT_TOUCH = "TRUE"*)
module uart_rx #(
    parameter BAUD_RATE = 115200,
    parameter CLOCK_FREQ = 100000000  // 系统时钟 100MHz
)(
    input wire clk,           // 系统时钟
    input wire rst_n,           // 重置信号
    input wire rx,            // UART 接收引脚
    output reg [7:0] data,    // 接收到的 8 位数据
    output reg valid          // 数据有效标志
);
  
    parameter BIT_PERIOD = CLOCK_FREQ / BAUD_RATE;

    reg [15:0] bit_cnt;
    reg [3:0] bit_index;
    reg [9:0] shift_reg;
    reg receiving;

    always @(posedge clk or negedge rst_n) begin
        if (!rst_n) begin
            bit_cnt <= 0;
            bit_index <= 0;
            shift_reg <= 10'b1111111111;
            receiving <= 0;
            valid <= 0;
        end else begin
            if (!receiving && rx == 0) begin  // 检测到起始位
                receiving <= 1;
                bit_cnt <= 0;
                bit_index <= 0;
            end else if (receiving) begin
                if (bit_cnt < BIT_PERIOD - 1) begin
                    bit_cnt <= bit_cnt + 1;
                end else begin
                    bit_cnt <= 0;
                    shift_reg <= {rx, shift_reg[9:1]};  // 移位
                    if (bit_index < 9) begin
                        bit_index <= bit_index + 1;
                    end else begin
                        receiving <= 0;
                        data <= shift_reg[8:1];  // 获取数据部分
                        valid <= 1;
                    end
                end
            end else begin
                valid <= 0;
            end
        end
    end
endmodule
